# -*- coding: utf-8 -*-
# @File      :MongoDBConnent
# @Author    :liaogan
# @Datetime  :2023/2/21 21:41
import pymongo,time


class MongoDB_Connect:

    def __init__(self,user='admin',password='sq',ip='192.168.73.131',port=27017):
        self.client = pymongo.MongoClient(f"mongodb://{user}:{password}@{ip}:{port}")
        #指定连接那个数据库
        self.db=self.client['sq-waimai']

    #新增数据
    def insert(self,collect,query,many=True):
        """
        :param collect:集合，对应数据库表名称
        :param query: 新增数据的值为字典{"key","values"}
        :param many: 控制是否需要增加多个数据
        :return:
        """
        # res_set=self.db[collect]
        if many:
            return self.db[collect].insert_one(query)
        else:
            return self.db[collect].insert_many(query)

    #查询数据
    def select(self,collect,query,many=True):
        res_set=self.db[collect]
        if many:
            res=res_set.find(query)
            return [one for one in res]
        else:
            return res_set.find_one(query)

    #更新数据
    def update(self,collect,myquery,newvalues,many=False):
        """

        :param collect:   集合，对应数据库表名称
        :param myquery:   更新数据表的条件
        :param newvalues: 更新数据对应的值
        :param many:      控制是否需要多个数据进行更新
        :return:
        """
        res_set=self.db[collect]
        if many:
            return res_set.update_one(myquery,{"$set":newvalues})
        else:
            return  res_set.update_many(myquery, {"$set":newvalues})

    #删除数据
    def delete(self,collect,query,many=True):
        res_set=self.db[collect]
        if many:
            res_set.delete_one(query)
        else:
            res_set.delete_many(query)



if __name__ == '__main__':
    db=MongoDB_Connect()
    # res=db.insert('categories',{"count":1111,"level":4,"name":"快餐便当2"})
    # print(res)

    res = db.select('categories',{'count':1111})
    # print(res)

    # res=db.update('categories',{"count":1111},{"name":f"快餐修改操作{time.time()}"},many=False)
    # print(res)

    # res=db.delete('categories',{'count':1111})
    print(res)